/**
 * 
 */
package com.guchenbo.example.freemark;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;

import freemarker.template.Template;

/**
 * @author Cre.Gu
 *
 */
public class GenerateFromDocTest {

	private Entity entity;
	private String baseBeanPath = "src/test/java/cre/sample/test/freemark/temp/domain";

	public String ftlPath = "src/test/java/cre/sample/test/freemark/temp/ftl";
	public String docPath = "src/test/java/soa/report/core/test/generate/doc";

	@Before
	public void setup() {

	}

	@Test
	public void test() throws Exception {
		entity = resolveFile("E:\\hwdev.xlsx");
		entity.setName("HwData");

		Map<Object, Object> root = new HashMap<Object, Object>();
		root.put("entity", entity);

		String createFile = entity.getName() + ".java";
		doCreateByFreemark(baseBeanPath, ftlPath, "bean.ftl", createFile, root);

		entity = resolveFile("E:\\hwdev2.xlsx");
		entity.setName("HwData2");

		root.clear();
		root.put("entity", entity);

		createFile = entity.getName() + ".java";
		doCreateByFreemark(baseBeanPath, ftlPath, "bean.ftl", createFile, root);

	}

	@Test
	public void test2() throws Exception {
		List<Field> fs = gainFields("E:\\hwdev2.xlsx");

		String tn = "HWDATA2";

		StringBuffer sb = new StringBuffer();
		sb.append("-- Create table");
		sb.append("\n");
		sb.append("create table " + tn);
		sb.append("\n");
		sb.append("(");
		sb.append("\n");
		sb.append("ID NUMBER(19) not null,");
		sb.append("\n");

		for (Iterator<Field> iterator = fs.iterator(); iterator.hasNext();) {
			Field field = (Field) iterator.next();
			String n = field.getName();

			sb.append(n + " varchar2(255)");
			if (iterator.hasNext()) {
				sb.append(",");
			}
			sb.append("\n");
		}
		sb.append(");");
		sb.append("\n");

		sb.append("-- Add comments to the columns ");
		sb.append("\n");
		for (Iterator<Field> iterator = fs.iterator(); iterator.hasNext();) {
			Field field = (Field) iterator.next();
			String n = field.getName();

			sb.append("comment on column " + tn + "." + n + " is '" + field.getComment() + "';");
			sb.append("\n");
		}

		System.out.println(sb.toString());
	}

	@Test
	public void test3() throws Exception {
		entity = resolveFile("E:\\swdev.xlsx");
	}

	public Entity readFile() throws Exception {
		return resolveFile("E:\\hwdev.xlsx");
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	Entity resolveFile(String file) throws Exception {
		InputStream is = new FileInputStream(file);

		Workbook wb = new XSSFWorkbook(is);
		Sheet sheet = wb.getSheetAt(0);

		Entity result = new Entity();
		List<Field> fields = new ArrayList<Field>();
		result.setFields(fields);

		List<String> coms = new ArrayList<String>();
		List<String> nams = new ArrayList<String>();

		List[] lists = { coms, nams };
		for (Row row : sheet) {
			List<String> ss = lists[row.getRowNum()];

			for (Cell cell : row) {
				ss.add(cell.getStringCellValue());
				System.out.println("headers.put(\"" + cell.getStringCellValue() + "\",\"\"" + ");");
			}
		}

		StringBuffer sb = new StringBuffer();
		sb.append("create table HWDATA2");
		sb.append("\n");
		sb.append("(");
		sb.append(" ID NUMBER(19) not null,");
		sb.append("\n");

		for (int i = 0; i < nams.size(); i++) {

			String n = nams.get(i);
			if ("Linkage ID".equals(n)) {
				n = "Linkage_ID";
			}

			Field f = new Field();

			f.setName(n);
			f.setComment(coms.get(i));
			f.setNamesg(f.getName());
			f.setType("String");

			fields.add(f);

			sb.append(n + " varchar2(255)");
			if (i < (nams.size() - 1)) {
				sb.append(",");
			}
			sb.append("\n");
		}
		sb.append(")");

		System.out.println(sb.toString());

		close(is);
		return result;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Field> gainFields(String file) throws Exception {
		List<Field> result = new ArrayList<Field>();
		InputStream is = new FileInputStream(file);

		Workbook wb = new XSSFWorkbook(is);
		Sheet sheet = wb.getSheetAt(0);

		List<String> coms = new ArrayList<String>();
		List<String> nams = new ArrayList<String>();

		List[] lists = { coms, nams };
		for (Row row : sheet) {
			List<String> ss = lists[row.getRowNum()];

			for (Cell cell : row) {
				ss.add(cell.getStringCellValue());
			}
		}

		for (int i = 0; i < nams.size(); i++) {

			String n = nams.get(i);
			if ("Linkage ID".equals(n)) {
				n = "Linkage_ID";
			}

			Field f = new Field();

			f.setName(n);
			f.setComment(coms.get(i));
			f.setNamesg(f.getName());
			f.setType("String");

			result.add(f);

		}

		close(is);
		return result;
	}

	protected void doCreateByFreemark(String beanPath, String ftlPath, String ftlName, String createFileName,
			Map<Object, Object> root) {
		try {
			Template temp = FreeMarkerUtil.getConfiguration(ftlPath).getTemplate(ftlName);

			String createFile = beanPath + "/" + createFileName;
			FileUtil.createDirectory(beanPath);
			File file = new File(createFile);
			if (file.exists())
				file.delete();

			OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8");
			BufferedWriter bw = new BufferedWriter(fw);
			temp.process(root, bw);

			bw.flush();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 关闭输入流
	 * 
	 * @param is
	 */
	public void close(InputStream is) {
		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
